package utils

import "strings"

/*
*

	1000W: consume:4536(ms)
*/
func RouteIncludesTopic(route, topic string) bool {
	return RouteIncludesTopic_0(strings.Split(route, "/"), strings.Split(topic, "/"))
}

func ParseRoute(route string) []string {
	return strings.Split(route, "/")
}

/*
*

	1000W:consume:730(ms)
*/
func RouteIncludesTopic_0(route []string, topic []string) bool {
	if len(route) == 0 {
		return len(topic) == 0
	}

	if len(topic) == 0 {
		return route[0] == "#"
	}

	if route[0] == "#" {
		return true
	}

	if (route[0] == "+") || (route[0] == topic[0]) {
		return RouteIncludesTopic_0(route[1:], topic[1:])
	}
	return false
}

/*
*

	1000W:consume:1841(ms)
*/
func RouteIncludesTopic_1(route string, topic string) bool {
	if len(route) == 0 {
		return len(topic) == 0
	}

	if len(topic) == 0 {
		return route[0] == '#'
	}

	if route[0] == '#' {
		return true
	}

	var route0, topic0 string

	route0, route = Split2StrV1(route, '/')
	topic0, topic = Split2StrV1(topic, '/')
	if (route0 == "+") || (route0 == topic0) {
		return RouteIncludesTopic_1(route, topic)
	}
	return false
}

/*
**

	路由匹配: (mqtt匹配方式)
*/
func MatchRoute(route, topic string) bool {
	return route == topic || RouteIncludesTopic_1(route, topic)
}

/*
*

	0：完全匹配

-1: 互相不包含

	1: route0 包含 route1
	2: route0 被包含 route1
*/
func CompareRoute(route0, route1 string) int {
	if route0 == route1 {
		return 0
	}

	if RouteIncludesTopic_1(route0, route1) {
		return 1
	}

	if RouteIncludesTopic_1(route1, route0) {
		return 2
	}

	return -1
}
